package com.s69.appback.service;

import com.s69.appback.dto.LoginUserDto;
import com.s69.appback.entity.BackendUser;
import com.s69.appback.entity.DevUser;
import com.s69.appback.mapper.BackendUserDao;
import com.s69.appback.mapper.DevUserDao;
import com.s69.appback.util.SessionUtils;
import com.s69.appback.vo.LoginUserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.UUID;

@Service
public class DevUserService {
    @Autowired
    DevUserDao devUserDao;
    @Autowired
    BackendUserDao backendUserDao;
    public LoginUserVo login(LoginUserDto userDto) {
        if (userDto.getUserType()==1){
            BackendUser backendUser=new BackendUser();
            backendUser.setUsercode(userDto.getAccount());
            backendUser.setUserpassword(userDto.getPassword());
            List<BackendUser> list = backendUserDao.queryAllBy(backendUser);
            if (list==null||list.size()==0){
                throw new RuntimeException("用户名或者密码错误!");
            }
            StringBuffer buffer=new StringBuffer();
            //token:uuid-用户名-id-用户类型-生成时间
            buffer.append(UUID.randomUUID().toString().replace("-",""));
            buffer.append("-"+list.get(0).getUsercode());
            buffer.append("-"+list.get(0).getId());
            buffer.append("-admin");
            buffer.append("-"+System.currentTimeMillis());
            SessionUtils.setToken(buffer.toString(),list.get(0));
            LoginUserVo vo=new LoginUserVo();
            vo.setToken(buffer.toString());
            vo.setUser(list.get(0));
            return vo;
        }else if (userDto.getUserType()==2){
            DevUser devUser=new DevUser();
            devUser.setDevcode(userDto.getAccount());
            devUser.setDevpassword(userDto.getPassword());
            List<DevUser> list = devUserDao.queryAllBy(devUser);
            if (list==null||list.size()==0){
                throw new RuntimeException("用户名或者密码错误!");
            }
            StringBuffer buffer=new StringBuffer();
            //token:uuid-用户名-id-用户类型-生成时间
            buffer.append(UUID.randomUUID().toString().replace("-",""));
            buffer.append("-"+list.get(0).getDevcode());
            buffer.append("-"+list.get(0).getId());
            buffer.append("-dev");
            buffer.append("-"+System.currentTimeMillis());
            SessionUtils.setToken(buffer.toString(),list.get(0));
            LoginUserVo vo=new LoginUserVo();
            vo.setToken(buffer.toString());
            vo.setUser(list.get(0));
            return vo;
        }else {
            throw new RuntimeException("无效的用户类型");
        }
    }
}
